<?php

namespace App\Models;
use App\Cache\BaseCache;

class QuickMsg extends BaseModel {
    //表明
    protected $table = 'quick_msg';
    //主键
    protected $primaryKey = 'id';

    //用户实体信息
    protected function getQuickMsgObejct($id, $model = null) {
        $quickMsg = $this->getQuickMsgModel($id, $model);
        if (isset($quickMsg->id) && $quickMsg->is_delete != 1) {
            $giftObject = array();
            $giftObject['msgId'] = $quickMsg->id;
            $giftObject['msg'] = $quickMsg->msg; //token
            return $giftObject;
        }
        return;
    }

    //获取礼物实体
    public function getQuickMsgModel($id, $model = '') {
        $modelCache = new BaseCache();
        $modelCache->method = 'get';
        $modelCache->cacheName = 'quickMsgModel';
        $modelCache->cachePar = array($id); //集合
        $retCache = $modelCache->HandleCache();
        if ($retCache !== 'NO_CACHE') {
            if (!isset($retCache->id)) {
                return;
            }
            return $retCache;
        }
        if (isset($model->id) && $model->id > 0) {
            $quickMsgmodel = $model;
        } else if ($id > 0) {
            $quickMsgmodel = $this->select('id', 'msg', 'is_delete')
                    ->where('id', '=', $id)
                    ->first();
        } else {
            $quickMsgmodel = 'CACHE_BREAKDOWN';
        }
        $modelCache->method = 'put';
        $modelCache->cacheValue = $quickMsgmodel;
        $modelCache->HandleCache();
        if (!isset($quickMsgmodel->id)) {
            return;
        }
        return $quickMsgmodel;
    }

    //获取礼物列表
    public function getQuickMsgList() {
        $modelCache = new BaseCache();
        $modelCache->method = 'get';
        $modelCache->cacheName = 'quickMsgList';
        $retCache = $modelCache->HandleCache();
        if ($retCache === 'CACHE_BREAKDOWN') {
            return array();
        }
        $data = array();
        if (is_array($retCache) && count($retCache) > 0) {
            $quickMsgs = $retCache;
            foreach ($quickMsgs as $quickMsg) {
                $index = $this->getQuickMsgObejct($quickMsg['id']);
                if (isset($index['msgId'])) {
                    $data[] = $index;
                }
            }
        } else {
            $quickMsgs = $this->select('id', 'msg', 'is_delete')
                    ->where('is_delete', '=', 0)
                    ->orderBy('sort', 'asc')
                    ->take(10)
                    ->get();
            foreach ($quickMsgs as $quickMsg) {
                $index = $this->getQuickMsgObejct($quickMsg->id, $quickMsg);
                if (isset($index['msgId'])) {
                    $modelCache->cacheValue[] = array('id' => $index['msgId']);
                    $data[] = $index;
                }
            }
            $modelCache->method = 'put';
            $modelCache->HandleCache();
        }
        return $data;
    }

}
